package czk.concrent.synControl;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/6/2 21:15
 */
// 同步，利用ReentrantLock
public class Test1 {
    public static void main(String[] args) throws InterruptedException {
        AwaitSignal awaitSignal=new AwaitSignal(5);
        // 线程a的休息室
        Condition condition1= awaitSignal.newCondition();
        // 线程b的休息室
        Condition condition2= awaitSignal.newCondition();
        // 线程c的休息室
        Condition condition3= awaitSignal.newCondition();
        new Thread(()->{
            awaitSignal.print("a",condition1,condition2);
        }).start();
        new Thread(()->{
            awaitSignal.print("b",condition2,condition3);
        }).start();
        new Thread(()->{
            awaitSignal.print("c",condition3,condition1);
        }).start();
        Thread.sleep(1*1000);
        awaitSignal.lock();
        try {
            // 刚开始，三个线程都在休息室，需要主线程唤醒
            // 先唤醒a,则是abc
            // 先唤醒b，则是bca
            // 先唤醒c,则是cab
            condition1.signal();
        }finally {
            // 解锁主线程
            awaitSignal.unlock();
        }
    }
}
class AwaitSignal extends ReentrantLock {
    private int loopNumber;

    public AwaitSignal(int loopNumber) {
        this.loopNumber = loopNumber;
    }
    public void print(String content,Condition current,Condition next ){
        for (int i = 0; i <loopNumber ; i++) {
            lock();
            try {
                try {
                    // 进入休息室
                    current.await();
                    // 输出内容
                    System.out.print(content);
                    // 唤醒下一个线程
                    next.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }finally {
                unlock();
            }
        }
    }
}
